package com.sec.etech.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.openbpm.sys.util.ContextUtil;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatisplus自动填充字段
 */
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        LocalDateTime localDateTime = LocalDateTime.now();

        if (ContextUtil.getCurrentUserId() != null) {
            Long uid = Long.parseLong(ContextUtil.getCurrentUserId());
            this.strictInsertFill(metaObject, "postuid", Long.class, uid);
            this.strictInsertFill(metaObject, "lastuid", Long.class, uid);
            this.strictInsertFill(metaObject, "postuid", String.class, uid.toString());
            this.strictInsertFill(metaObject, "lastuid", String.class, uid.toString());
            this.strictInsertFill(metaObject, "createBy", String.class, uid.toString());
            this.strictInsertFill(metaObject, "updateBy", String.class, uid.toString());
        }
        this.strictInsertFill(metaObject, "postdate", Date.class, date);
        this.strictInsertFill(metaObject, "lastdate", Date.class, date);
        this.strictInsertFill(metaObject, "postdate", LocalDateTime.class, localDateTime);
        this.strictInsertFill(metaObject, "lastdate", LocalDateTime.class, localDateTime);
        this.strictInsertFill(metaObject, "createTime", Date.class, date);
        this.strictInsertFill(metaObject, "updateTime", Date.class, date);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ContextUtil.getCurrentUserId() != null) {
            Long uid = Long.parseLong(ContextUtil.getCurrentUserId());
            this.strictUpdateFill(metaObject, "lastuid", Long.class, uid);
            this.strictUpdateFill(metaObject, "lastuid", String.class, uid.toString());
            this.strictInsertFill(metaObject, "updateBy", String.class, uid.toString());
        }
        Date date = new Date();
        LocalDateTime localDateTime = LocalDateTime.now();
        this.strictUpdateFill(metaObject, "lastdate", Date.class, date);
        this.strictUpdateFill(metaObject, "lastdate", LocalDateTime.class, localDateTime);
        this.strictInsertFill(metaObject, "updateTime", Date.class, date);
    }
}
